package com.example.openim.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.openim.domain.SubSocket;
import com.example.openim.enums.ErrorCode;
import com.example.openim.service.SubSocketService;
import com.example.openim.service.TYRZUserService;
import com.example.openim.utils.AjaxResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @description: 外放接口
 * @author: xhq
 * @create: 2025-11-13 15:15
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SubSocketServiceImpl implements SubSocketService {

    @Autowired
    private TYRZUserService tyrzUserService;

    private final MongoTemplate mongoTemplate;

    /**
     * 获取消息未读数
     *
     * @param code
     * @return
     */
    @Override
    public AjaxResult getSubscript(String code) {
        //获取用户信息
        JSONObject jsonObject = tyrzUserService.queryUserInfo(code);
        if (jsonObject == null){
            return AjaxResult.error(ErrorCode.ERROR.getCode(),"获取用户信息失败");
        }
        String phone = jsonObject.getString("usridtel");
        if (StringUtils.isBlank(phone)){
            return AjaxResult.error(ErrorCode.ERROR.getCode(),"获取用户信息失败");
        }
        log.info("获取到的手机号："+phone);
        Query query = new Query(Criteria.where("phone_number").is(phone));
        SubSocket subSocket = mongoTemplate.findOne(query, SubSocket.class, "sub_socket");
        Integer count = subSocket.getCount();
        if (Objects.isNull(count)){
            return AjaxResult.error(ErrorCode.ERROR.getCode(),"查询未读数失败");
        }
        return AjaxResult.success(count);
    }

}
